import paramiko
import tkinter
import time
import threading

class Ssh():
    def __init__(self,addr,path) -> None: 
        print(addr,path)
        self.tk_mainwindow = tkinter.Tk()
        self.tk_mainwindow.title('日志监听')

        self.horizontal = 1600
        self.vertical = 800

        self.ssh_host = tkinter.StringVar()
        self.ssh_username = tkinter.StringVar()
        self.ssh_password = tkinter.StringVar()
        self.log_path = path

        addr_list = addr.split('&')
        if len(addr_list) == 2:
            self.ssh_host.set(addr_list[0])
            user_info = addr_list[1].split('/')
            if len(user_info) == 2:
                self.ssh_username.set(user_info[0])
                self.ssh_password.set(user_info[1])
                
        
        self.ssh_command = tkinter.StringVar()

        self.entry_list = []
        self.ssh = paramiko.SSHClient()

        self.tail_thread = threading.Thread(target=self.tail_f)
        self.tail_thread.daemon = True
        self.is_running = False
        self.text_flag = False
        self.is_top = False
        
        self.showWidget()
        self.text.insert(tkinter.END, '监听日志为:'+self.log_path +"\n")
        self.ssh_connect()
        self.tk_mainwindow.mainloop()
        
    def showWidget(self):
        # self.tk_mainwindow.geometry(f'{self.horizontal}x{self.vertical}')
        tkinter.Label(self.tk_mainwindow, text="host").grid(row=0,column=1)
        self.host_entry = tkinter.Entry(self.tk_mainwindow,textvariable = self.ssh_host,width=30)
        self.host_entry.grid(row=0,column=2,sticky='we')

        tkinter.Label(self.tk_mainwindow, text="用户").grid(row=0,column=3)
        self.username_entry = tkinter.Entry(self.tk_mainwindow,textvariable = self.ssh_username,width=30)
        self.username_entry.grid(row=0,column=4,sticky='we')

        tkinter.Label(self.tk_mainwindow, text="密码").grid(row=0,column=5)
        self.password_entry = tkinter.Entry(self.tk_mainwindow,textvariable = self.ssh_password,width=30)
        self.password_entry.grid(row=0,column=6,sticky='we')

        self.entry_list.append(self.host_entry)
        self.entry_list.append(self.username_entry)
        self.entry_list.append(self.password_entry)
        self.button_connect = tkinter.Button(self.tk_mainwindow, text="重新连接", bg="lightblue",command=self.ssh_connect)
        self.button_connect.grid(row=0,column=7,sticky='ew')

        self.button_tail = tkinter.Button(self.tk_mainwindow, text="开始打印", bg="lightblue",command=self.text_control ,state = 'disabled')
        self.button_tail.grid(row=1,column=0,sticky='ew',columnspan = 5)
        self.button_clear = tkinter.Button(self.tk_mainwindow, text="清空", bg="lightblue",command=lambda:self.text.delete('1.0', 'end'))
        self.button_clear.grid(row=1,column=5,sticky='ew',columnspan = 4)
        self.button_top = tkinter.Button(self.tk_mainwindow, text="窗口置顶", bg="lightblue",command=self.top_control)
        self.button_top.grid(row=1,column=7,sticky='ew')


        self.text = tkinter.Text(self.tk_mainwindow)
        scrollbar_y = tkinter.Scrollbar(self.tk_mainwindow, command=self.text.yview)
        self.text.config(yscrollcommand=scrollbar_y.set)
        scrollbar_y.grid(row=2, column=7, sticky='ns')
        self.text.grid(row=2, column=0, sticky='nsew',columnspan = 7)




        self.tk_mainwindow.grid_rowconfigure(2, weight=1)
        self.tk_mainwindow.grid_columnconfigure(0, weight=1)

        # self.command_entry = tkinter.Entry(self.tk_mainwindow,textvariable = self.ssh_command)
        # self.command_entry.grid(row=3,column=0,sticky='we',columnspan = 7)
        # self.button_commit = tkinter.Button(self.tk_mainwindow, text="执行", bg="lightblue",command=lambda:self.do_command(self.ssh,self.command_entry.get()))
        # self.button_commit.grid(row=3,column=7,sticky='ew')

        

    def top_control(self):
        if self.is_top:
            self.tk_mainwindow.wm_attributes('-topmost', 0)
            self.button_top.config(text='窗口置顶')
        else:
            self.tk_mainwindow.wm_attributes('-topmost', 1)
            self.button_top.config(text='取消置顶')
        self.is_top = not self.is_top
        
    def ssh_connect(self):
        try:
            print('try connecting')
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            host = self.ssh_host.get()
            user = self.ssh_username.get()
            pwd = self.ssh_password.get()
            print(f'host={host},user={user},password={pwd}')
            self.ssh.connect(host, username=user, password=pwd)
            self.ssh.get_transport().set_keepalive(30)
            self.tail_thread_control()
            for entry in self.entry_list:
                entry.config(state = 'readonly')
            self.button_connect.config(text='已连接',state='disabled',bg= 'lightgreen')
            self.button_tail.config(state='normal')
            print('successful connect')
        except Exception as e:
            self.ssh.close()
            print('fail connect')
            print(e)
            
            

    def do_command(self,ssh,cmd):
        if self.ssh.get_transport() is not None:
            try:
                stdin, stdout, stderr = ssh.exec_command(cmd)
                result = stdout.read().decode('gbk')
                print(stdout.read().decode('gbk'))
                err = stderr.read().decode('gbk')
                self.append_text(result)
                self.append_text(err)
                self.ssh_command.set("")
            except Exception as e:
                self.append_text(e)
                print(e)
        else:
            self.append_text("ssh未连接")

    def text_control(self):
        if self.text_flag:
            self.append_text("==========暂停打印==========\n")
            print('stop show logs')
            self.text_flag = False
            self.button_tail.config(text='开始打印')
        else:
            self.text_flag = True
            self.append_text("----------开始打印----------\n")
            print('show logs')
            self.button_tail.config(text='暂停打印')

    def tail_thread_control(self):
        if self.ssh.get_transport() is not None:
            if not self.tail_thread.is_alive():
                try:
                    self.is_running = True
                    self.tail_thread.start()
                except Exception as e:
                    self.append_text(e)
                    print(e)
            else:
                print("线程正在运行")
        else:
            print("ssh未连接")

    def tail_f(self):
        cmd = f"tail -f {self.log_path}\n"
        self.channel = self.ssh.invoke_shell()
        
        self.channel.send(cmd)
        while self.is_running:
            # time.sleep(0.1)
            try:
                output = self.channel.recv(1024).decode('utf-8',errors='replace')
                if output:
                    self.append_text(output)
            except Exception as e:
                print(f"Error: {e}")
                self.append_text(e)
                break

        self.button_tail.config(text='监听日志')
        self.is_running = False
        self.channel.close()
        self.tail_thread.join()

    def append_text(self, text):
        if self.text_flag:
            # 将新文本追加到 Text 组件
            self.text.insert(tkinter.END, text)
            self.text.see(tkinter.END)  # 自动滚动到底部


if __name__ == '__main__':
    Ssh("10.20.162.81&ta6/Cfcs2@073861","/home/ta6/ta6_gtfz/dtl-web-starter/dtl-web-starter/logs/dtl-web.log")

